import PerfectScrollbar from 'perfect-scrollbar';
export default function ($) {
    'use strict';
    window.addEventListener('load', function () {
        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        var forms = document.getElementsByClassName('needs-validation');
        // Loop over them and prevent submission
        var validation = Array.prototype.filter.call(forms, function (form) {
            form.addEventListener('submit', function (event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);

    $('.globalModal').modal('show')

    $(document).on('click', '[data-nav-target]', function () {
        var $this = $(this),
            target = $this.data('nav-target');

        if ($('body').hasClass('lyear-layout-sidebar-close')) {
            $('body').removeClass('lyear-layout-sidebar-close');
        }

        $('.lyear-layout-sub-column > ul').hide();
        $('.lyear-layout-sub-column ' + target).fadeIn(500);
        $this.parent().siblings().removeClass('active');
        $this.parent().addClass('active');
        $this.parent().tooltip('hide');
        return false;
    });

    // 停止
    $("body").on('click', '[data-stopPropagation]', function (e) {
        e.stopPropagation();
    });

    // 提示
    if ($('[data-toggle="tooltip"]')[0]) {
        $('[data-toggle="tooltip"]').tooltip({
            "container": 'body',
        });
    }

    // 滚动条
    if ($('.lyear-scroll')[0]) {
        $('.lyear-scroll').each(function () {
            new PerfectScrollbar(this, {
                swipeEasing: false,
                suppressScrollX: true
            });
        });
    }

    // 侧边栏
    $(document).on('click', '.lyear-aside-toggler', function () {
        $('.lyear-layout-sidebar').toggleClass('lyear-aside-open');
        $("body").toggleClass('lyear-layout-sidebar-close');

        if ($('.lyear-mask-modal').length == 0) {
            $('<div class="lyear-mask-modal"></div>').prependTo('body');
        } else {
            $('.lyear-mask-modal').remove();
        }
    });

    // 遮罩层
    $(document).on('click', '.lyear-mask-modal', function () {
        $(this).remove();
        $('.lyear-layout-sidebar').toggleClass('lyear-aside-open');
        $('body').toggleClass('lyear-layout-sidebar-close');
    });

    // 侧边栏导航
    $(document).on('click', '.nav-item-has-subnav > a', function () {
        var subnavToggle = $(this);
        var navHasSubnav = subnavToggle.parent();
        var subnav = navHasSubnav.find('.nav-subnav').first();
        navHasSubnav.siblings().find('.nav-subnav:visible').slideUp(500).parent().removeClass('open');
        subnav.slideToggle(300, function () {
            navHasSubnav.toggleClass('open');
        });
    });

    // 读取cookie中的主题设置
    var the_logo_bg = $.cookie('the_logo_bg'),
        the_header_bg = $.cookie('the_header_bg'),
        the_sidebar_bg = $.cookie('the_sidebar_bg');

    if (the_logo_bg) $('body').attr('data-logobg', the_logo_bg);
    if (the_header_bg) $('body').attr('data-headerbg', the_header_bg);
    if (the_sidebar_bg) $('body').attr('data-sidebarbg', the_sidebar_bg);

    // 处理主题配色下拉选中
    $(".dropdown-skin :radio").each(function () {
        var $this = $(this),
            radioName = $this.attr('name');
        switch (radioName) {
            case 'logo_bg':
                $this.val() == the_logo_bg && $this.prop("checked", true);
                break;
            case 'header_bg':
                $this.val() == the_header_bg && $this.prop("checked", true);
                break;
            case 'sidebar_bg':
                $this.val() == the_sidebar_bg && $this.prop("checked", true);
        }
    });

    // 设置主题配色
    function setTheme(input_name, data_name) {
        $("input[name='" + input_name + "']").click(function () {
            $('body').attr(data_name, $(this).val());
            $.cookie('the_' + input_name, $(this).val());
        });
    }
    setTheme('sidebar_bg', 'data-sidebarbg');
    setTheme('logo_bg', 'data-logobg');
    setTheme('header_bg', 'data-headerbg');

    // 选项卡
    $('#iframe-content').multitabs({
        iframe: true,
        refresh: 'no',  // iframe中页面是否刷新，'no'：'从不刷新'，'nav'：'点击菜单刷新'，'all'：'菜单和tab点击都刷新'
        nav: {
            backgroundColor: '#ffffff',
            maxTabs: 35, // 选项卡最大值
        },
        dbclickRefresh: true,
        init: [{
            type: 'main',
            title: '首页',
            url: globOption.dashboard
        }]
    });

    $(document).on('click', '.nav-item .multitabs', function () {
        $('.nav-item').removeClass('active');
        $('.nav-subnav li').removeClass('active');
        $(this).parent('li').addClass('active');
        $(this).parents('.nav-item-has-subnav').addClass('open').first().addClass('active');
    });


    // 工具提示
    if ($('[data-toggle="tooltip"]')[0]) {
        $('[data-toggle="tooltip"]').tooltip({
            "container": 'body',
        });
    }

    // POP弹出框
    if ($('[data-toggle="popover"]')[0]) {
        $('[data-toggle="popover"]').popover();
    }

    // 关闭卡片
    $(document).on('click', '.card-btn-close', function () {
        $(this).closest('.card').fadeOut(150, function () {
            if ($(this).parent().children().length == 1) {
                $(this).parent().remove();
            } else {
                $(this).remove();
            }
        });
    });

    // 卡片收缩与打开
    $(document).on('click', '.card-btn-slide', function () {
        $(this).toggleClass('rotate-180').closest('.card').find('.card-body').slideToggle();
    });

    /**
     * 如果页面中需要用到滚动条，请先导入perfect-scrollbar.min.js
     */
    if ($('.lyear-scroll')[0]) {
        $('.lyear-scroll').each(function () {
            new PerfectScrollbar(this, {
                swipeEasing: false,
                suppressScrollX: true
            });
        });
    }

    // 颜色选取
    $('.js-colorpicker').each(function () {
        var $colorpicker = $(this);
        var $colorpickerMode = $colorpicker.data('colorpicker-mode') ? $colorpicker.data('colorpicker-mode') : 'auto';
        $colorpicker.colorpicker({
            'format': $colorpickerMode,
        });
    });

    // 日期选择器
    $("[data-provide = 'datepicker']").each(function () {
        var options = {
            language: 'zh-CN',  // 默认简体中文
            multidateSeparator: ', ' // 默认多个日期用,分隔
        }

        options = $.extend(options, getDataOptions($(this)));

        if ($(this).prop("tagName") != 'INPUT') {
            options.inputs = [$(this).find('input:first'), $(this).find('input:last')];
        }

        $(this).datepicker(options);
    });

    // 时间选择器
    $("[data-provide = 'clockpicker']").each(function () {
        $(this).clockpicker({
            donetext: 'Done'
        });
    });

    // 时间日期选择器
    $("[data-provide = 'datetimepicker']").each(function () {
        var options = {
            locale: "zh-cn",
        }

        options = $.extend(options, getDataOptions($(this)));

        if ($(this).prop("tagName") != 'INPUT') {
            options.inputs = [$(this).find('input:first'), $(this).find('input:last')];
        }
        $(this).datetimepicker(options);
    });

    // 标签
    $('.js-tags-input').each(function () {
        var $this = $(this);
        $this.tagsInput({
            height: $this.data('height') ? $this.data('height') : '36px',
            width: '100%',
            defaultText: $this.attr("placeholder"),
            removeWithBackspace: true,
            delimiter: [',']
        });
    });

    // 复选框全选
    $("#check-all").change(function () {
        if ($boxname = $(this).data('name')) {
            $(this).closest('table').find("input[name='" + $boxname + "']").prop('checked', $(this).prop("checked"));
        } else {
            $(this).closest('table').find(".custom-checkbox input[type='checkbox']").prop('checked', $(this).prop("checked"));
        }
    });

    // iframe打开tab
    $(document).on('click', '.newTab', function () {
        parent.$(parent.document).data('multitabs').create({
            iframe: true,
            title: $(this).attr('title') ? $(this).attr('title') : '标题',
            url: $(this).data('url') ? $(this).data('url') : '/admin/about'
        }, true);
    });

    //水印
    function setWatermark(str1, str2) {
        var id = '1.23452384164.123412415'

        if (document.getElementById(id) !== null) {
            document.body.removeChild(document.getElementById(id))
        }

        var can = document.createElement('canvas')
        // 设置canvas画布大小
        can.width = 250
        can.height = 80

        var cans = can.getContext('2d')
        cans.rotate(-20 * Math.PI / 180) // 水印旋转角度
        cans.font = '15px Vedana'
        cans.fillStyle = '#666666'
        cans.textAlign = 'center'
        cans.textBaseline = 'Middle'
        cans.fillText(str1, can.width / 2, can.height) // 水印在画布的位置x，y轴
        cans.fillText(str2, can.width / 2, can.height + 22)

        var div = document.createElement('div')
        div.id = id
        div.style.pointerEvents = 'none'
        div.style.top = '40px'
        div.style.left = '0px'
        div.style.opacity = '0.15'
        div.style.position = 'fixed'
        div.style.zIndex = '100000'
        div.style.width = document.documentElement.clientWidth + 'px'
        div.style.height = document.documentElement.clientHeight + 'px'
        div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
        document.body.appendChild(div)
        return id
    }

    var str1 = globOption.fullName;
    var now = (new Date()).toLocaleString();
    var id = setWatermark(str1, now)
    if (document.getElementById(id) === null) {
        id = setWatermark(str1, now)
    }

}
